package com.yunshang.ysmall.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.pingplusplus.Pingpp;
import com.pingplusplus.exception.APIConnectionException;
import com.pingplusplus.exception.APIException;
import com.pingplusplus.exception.AuthenticationException;
import com.pingplusplus.exception.ChannelException;
import com.pingplusplus.exception.InvalidRequestException;
import com.pingplusplus.exception.RateLimitException;
import com.pingplusplus.model.Charge;
import com.pingplusplus.util.WxpubOAuth;
import com.yunshang.ysmall.model.MbAddrInfo;
import com.yunshang.ysmall.model.MemberInfo;
import com.yunshang.ysmall.model.OrderInfo;
import com.yunshang.ysmall.model.OrderItemInfo;
import com.yunshang.ysmall.service.MemberService;
import com.yunshang.ysmall.util.Constants;
import com.yunshang.ysmall.util.DateUtils;
import com.yunshang.ysmall.util.HttpClientUtils;
import com.yunshang.ysmall.util.MD5Utils;

@Controller
@RequestMapping("/member")
public class MemberController {
	private static Logger logger = LoggerFactory.getLogger(OrderController.class);
	@Resource
	MemberService memberService;
	
	public static final String ROOT = "src/main/resources/static/upload-dir";
	
	public static final String url = "http://211.219.83.86:8090/scapi.aspx?client_id=YUNSHANG";
	public static final String key = "123456";
	
	@ResponseBody
	@RequestMapping("/login")
	public String login(MemberInfo memberInfo,HttpServletRequest request,Model model){
		String schemaName =  "GET_USER_LOGIN";
		try {
			String param = URLEncoder.encode("{\"USER_ALIAS\":\""+memberInfo.getMemberId()+"\",\"PASSWORD1\":\""+MD5Utils.MD5(memberInfo.getPassword()).toLowerCase()+"\"}","utf-8");
			String ndate = DateUtils.currentDate("HHmmss");
			String md5 = MD5Utils.MD5("YUNSHANG"+key+ndate).toLowerCase();
			String requestUrl = url+"&schema_name="+schemaName+"&parameter="+param+"&ndate="+ndate+"&md5="+md5;
			String result = HttpClientUtils.httpGet(requestUrl);
			System.out.println("result:"+result);
		// {"result":"success","total":1,"data":[{"NAME":"乔江2","DWALLET":"0.74","USER_ALIAS":"AN809702","PASSWORD":"96e79218965eb72c92a549dd5a330112","ISLOGIN":1.0}]};
			JSONObject jsonObject = JSONObject.parseObject(result);
			if("success".equals(jsonObject.getString("result"))){
				JSONObject data = jsonObject.getJSONArray("data").getJSONObject(0);
				if(!"".equals(data.getString("NAME"))){
					memberInfo.setNickName(data.getString("NAME"));
				}else{
					return "{\"result\":\"fail\"}";
				}
				if(!"".equals(data.getString("DWALLET"))){
					memberInfo.setBonusBalance(data.getBigDecimal("DWALLET"));
				}
				memberService.loginHandle(memberInfo);
//				model.addAttribute("memberInfo", memberInfo);
				request.getSession().setAttribute(Constants.LOGIN_MEMBER, memberInfo);
				request.getSession().setAttribute(Constants.MEMBER_ID, memberInfo.getMemberId());
				
				return "{\"result\":\"success\"}";
			}
			return "{\"result\":\"fail\"}";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "{\"result\":\"fail\"}";
		}
	}
	
	@RequestMapping("/wechat")
	public String wechat(String code,HttpServletRequest request, Model model) {
		logger.info("###########################");
		logger.info("code:"+code);
		if(code == null){
			return null;
		}
		try {
			String openId = WxpubOAuth.getOpenId("wx0c79bdb59eb72939", "a511700e96b37ca88f10c762e176991c", code);
//			String openId ="o0qua0_mj3wJD6YwipdgyBTpWZ9U";
			logger.info("openId:"+openId);
			logger.info("###########################");
			OrderInfo orderInfo = (OrderInfo)request.getSession().getAttribute("orderInfo");
			orderInfo.setOpenId(openId);
			model.addAttribute("orderInfo", orderInfo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/mall/prepay2";
	}
	@RequestMapping("/main")
	public String main(HttpServletRequest request,Model model){
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}
		return "/mall/mbmain";
	}
	
	@RequestMapping("/prepay/{step}")
	public String prepay(@PathVariable("step") Integer step,HttpServletRequest request,Model model){
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}
		MbAddrInfo mbAddrInfo = memberService.getAddrByMemberId((String)request.getSession().getAttribute(Constants.MEMBER_ID));
		model.addAttribute("mbAddrInfo", mbAddrInfo);
		List<OrderItemInfo> itemList = new ArrayList<OrderItemInfo>();
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setMemberId(mbAddrInfo.getMemberId());
		//直接购买进入
		if(1== step){
			OrderItemInfo itemInfo = new OrderItemInfo();
			System.out.println("###############");
			System.out.println(request.getParameter("productId"));
			System.out.println(request.getParameter("productName"));
			System.out.println(request.getParameter("count"));
			System.out.println(request.getParameter("price"));
			System.out.println(request.getParameter("bonus"));
			System.out.println("###############");
			itemInfo.setProductId(request.getParameter("productId"));
			itemInfo.setProName(request.getParameter("productName"));
			itemInfo.setSmallImgPath(request.getParameter("smallImgPath"));
			itemInfo.setCount(Integer.parseInt(request.getParameter("count")));
			itemInfo.setTransAmt(new BigDecimal(request.getParameter("price")));
			itemInfo.setTransBonus(new BigDecimal(request.getParameter("bonus")));
			orderInfo.setTransAmt(itemInfo.getTransAmt().multiply(new BigDecimal(itemInfo.getCount())));
			orderInfo.setTransBonus(itemInfo.getTransBonus().multiply(new BigDecimal(itemInfo.getCount())));
			itemList.add(itemInfo);
		}
		//购物车结算进入
		if(2== step){
			Map<String,OrderItemInfo> cartMap = (Map<String,OrderItemInfo>) request.getSession().getAttribute(Constants.MEMBER_CART);
			Map<String,OrderItemInfo> checkedMap = (Map<String,OrderItemInfo>) request.getSession().getAttribute(Constants.CHECKED_CART);
			if(Integer.parseInt(request.getParameter("itemCount")) != checkedMap.size()){
				return "/mall/cart";
			}
			BigDecimal transAmt = BigDecimal.ZERO;
			BigDecimal transBonus = BigDecimal.ZERO;
			for (String productId : checkedMap.keySet()) {
				OrderItemInfo checkdItem = checkedMap.get(productId);
				itemList.add(checkdItem);
				transAmt = transAmt.add(checkdItem.getTransAmt().multiply(new BigDecimal(checkdItem.getCount())));
				transBonus = transBonus.add(checkdItem.getTransBonus().multiply(new BigDecimal(checkdItem.getCount())));
				cartMap.remove(productId);
			}
			checkedMap.clear();
			orderInfo.setTransAmt(transAmt);
			orderInfo.setTransBonus(transBonus);
			request.getSession().setAttribute(Constants.MEMBER_CART, cartMap);
		}
		
		model.addAttribute("itemList", itemList);
		request.getSession().setAttribute("sureList", itemList);
		model.addAttribute("orderInfo", orderInfo);
		return "/mall/prepay";
	}
	
	@ResponseBody
	@RequestMapping("/dopay")
	public String dopay(OrderInfo orderInfo,HttpServletRequest request,Model model){
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}
		MemberInfo memberInfo = (MemberInfo)request.getSession().getAttribute(Constants.LOGIN_MEMBER);
		if(orderInfo.getTransBonus().compareTo(memberInfo.getBonusBalance()) > 0){
			return "{\"result\":\"fail\",\"msg\":\"会员积分不足\"}";
		}
		
//		if("wx".equals(orderInfo.getPayChannel()) && orderInfo.getOpenId() == null){
//			request.getSession().setAttribute("orderInfo", orderInfo);
//			return "{\"result\":\"success2\",\"msg\":\"http://localhost:8080/member/wechat?code=1234\"}";
//		}
		
		
		String ua = request.getHeader("user-agent").toLowerCase();
		logger.info("ua:"+ua);
		if(ua.indexOf("micromessenger") > 0){
			if("wx".equals(orderInfo.getPayChannel()) && orderInfo.getOpenId() == null){
				String url;
				try {
					url = WxpubOAuth.createOauthUrlForCode("wx0c79bdb59eb72939", "http://www.houheshangpin.com/member/wechat", false);
					request.getSession().setAttribute("orderInfo", orderInfo);
					return "{\"result\":\"success2\",\"msg\":\""+url+"\"}";
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if("ali".equals(orderInfo.getPayChannel()) ){
				return "{\"result\":\"fail\",\"msg\":\"请在右上角用浏览器打开\"}";
			}
		}
		
		
		
		int ran = (int)(Math.random()*9000) + 1000;
		orderInfo.setOrderId("HH"+DateUtils.currentDate("MMddHHmmss")+ran);
		orderInfo.setOrderDate(DateUtils.currentDate("yyyyMMdd"));
		orderInfo.setOrderTime(DateUtils.currentDate("HHmmss"));
		orderInfo.setOrderStatus(0);
		if(memberService.saveOrder(orderInfo)){
			List<OrderItemInfo> itemList = (List<OrderItemInfo>)request.getSession().getAttribute("sureList");
			for (OrderItemInfo orderItemInfo : itemList) {
				orderItemInfo.setOrderId(orderInfo.getOrderId());
				memberService.saveOrderItem(orderItemInfo);
			}
		}
		
		Pingpp.apiKey = "sk_live_az9uXH484iX9eDKGW5rjfPmL";
		Pingpp.privateKey = "-----BEGIN PRIVATE KEY-----\n" +
                "MIICXAIBAAKBgQChXY7SytFezkMSpyaWbh90ZWNdjERZVuSb6OcqRIILXA7o4LsP\n" + 
                "ZCIZly2vlJ5xjSAe/DiEGI1siHRuHdYghDWyzg+CfAQLJiwXI+7+4ffdZss9hKkZ\n" + 
                "EBYjYjt7OgtRUxrAob/YWF//HBaxCkhgAWoerbf/oORm+fNAHGNwYOUQ2wIDAQAB\n" + 
                "AoGAMUnUgEp3HVA/aIkp3jUQ4oq9iSt5DRjfh0fipCR83F9oJnXObWsWh16IE+N/\n" + 
                "agvDTfOYh7DAMfCUL7ZpW1FG3TSfAvnhrT5q+v8s0dYnhU7ANZ9iKpHXK2y+wu/3\n" + 
                "2u6KbjZqopsXrMhQzaV4zQkMljonU1MnxL6Bjqo+xmYamWECQQDRiJ0jG5qToHjs\n" + 
                "DOasY8vi7aCtv1JDLGWIw5eCQghM98yYiuA/kLB34OGYzdDlTg65rgECGmOttOQ3\n" + 
                "jgEpzFJTAkEAxSZmKsjJX9/gSBnxFvIFASXc47RSPv1eWJvueftuIZAu05y/WFbk\n" + 
                "cilNvSfChX3aNOHlheoP5103JGzeFIeGWQJBAIxF6vyv5CHkkk9kq6DJBpua/bCT\n" + 
                "npy9whN27Z0UW747Pkr43ftv/9OhRyYm0yxPv2fq513jEMwfh5DxjjHPSWUCQDQy\n" + 
                "GWSEakQ22oNcUucXRlnqc1PZ3tiMbhkZl4a2GY9LRAqEemhiAPN0mf9VcnuzOT08\n" + 
                "/W557KH9nObI5/cZdmkCQAuo/TirHFdBo0lLsIBAT5SvK5Gwd2x4Ru0NOvyZNnb1\n" + 
                "fEnjp0itbyoeT0Jk6Cmmml9rh3pDcXgIArbdYSpM8Yg=\n" +                     
                "-----END PRIVATE KEY-----\n";
		Charge charge = null;
		Map<String, Object> chargeParams = new HashMap<String, Object>();
		chargeParams.put("order_no", orderInfo.getOrderId());
		chargeParams.put("amount", orderInfo.getTransAmt().movePointRight(2).toString());// 订单总金额, 人民币单位：分（如订单总金额为 1 元，此处请填 100）
		Map<String, String> app = new HashMap<String, String>();
		app.put("id", "app_8Wrz5CHCKCqLzTab");
		chargeParams.put("app", app);
		if("ali".equals(orderInfo.getPayChannel())){
			chargeParams.put("channel", "alipay_wap");  //alipay_wap 支付宝手机网页 wx_pub_qr 微信公众号支付 wx_wap 微信wap
			Map<String, String> extra = new HashMap<String, String>();
			  //success_url 和 cancel_url 在本地测试不要写 localhost ，写 127.0.0.1，URL 后面不要加自定义参数
			  extra.put("success_url", "http://www.houheshangpin.com/member/notify");
			  extra.put("cancel_url", "http://www.houheshangpin.com/member/notify");
			  chargeParams.put("extra", extra);
		}else{
			chargeParams.put("channel", "wx_pub");  //alipay_wap 支付宝手机网页 wx_pub_qr 微信公众号支付 wx_wap 微信wap
				Map<String, String> extra = new HashMap<String, String>();
				  //success_url 和 cancel_url 在本地测试不要写 localhost ，写 127.0.0.1，URL 后面不要加自定义参数
				  extra.put("open_id", orderInfo.getOpenId());
				  chargeParams.put("extra", extra);
		}
		
		chargeParams.put("currency", "cny");
		chargeParams.put("client_ip", "139.224.227.142");
		chargeParams.put("subject", "厚和尚品");
		chargeParams.put("body", "厚和尚品");
		
		  
		try {
			charge = Charge.create(chargeParams);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info(charge.toString());
//		return "{\"result\":\"success\",\"data\":\""+charge.toString()+"\"}";
		return charge.toString();
	}
	
	
	

	@RequestMapping("/notify")
	public String notify(String result,String out_trade_no,HttpServletRequest request,Model model){
		String resultStr = "交易成功";
		model.addAttribute("result", resultStr);
		model.addAttribute("orderNo", out_trade_no);
		return "/mall/paynotify";
	}
	
	@RequestMapping("/addaddress")
	public String addaddress(HttpServletRequest request,Model model){
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}
		return "/mall/addaddress";
	}
	
	@RequestMapping("/pay.htm")
	public String paythm(HttpServletRequest request,Model model){
		return "/mall/pay";
	}
	
	@RequestMapping("/saveaddr")
	public String saveaddr(MbAddrInfo mbAddrInfo,HttpServletRequest request,Model model){
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}
		mbAddrInfo.setMemberId((String)request.getSession().getAttribute(Constants.MEMBER_ID));
		mbAddrInfo.setFullAddress(mbAddrInfo.getProvince()+" "+mbAddrInfo.getCity()+" "+mbAddrInfo.getDistrict()+" "+mbAddrInfo.getAddress());
		memberService.addMbAddr(mbAddrInfo);
		return "redirect:/member/prepay";
	}
	
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,Model model){
		request.getSession().removeAttribute(Constants.LOGIN_MEMBER);
		return "/index";
	}
	
	@RequestMapping("/orderlist/{otype}")
	public String orderlist(@PathVariable("otype") String otype,HttpServletRequest request,Model model){
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("startIndex", 0);
		params.put("pageSize", 10);
		String title = "";
		switch (otype) {
		case "all":
			params.put("orderStatus", null);
			title = "全部订单";
			break;
		case "waitpay":
			params.put("orderStatus", "0");
			title = "待支付订单";
			break;
		case "waitship":
			params.put("orderStatus", "2");
			params.put("transferStatus", "0");
			title = "待发货订单";
			break;
		case "shiped":
			params.put("orderStatus", "2");
			params.put("transferStatus", "2");
			title = "已发货订单";
			break;
		case "done":
			params.put("orderStatus", "2");
			params.put("transferStatus", "2");
			title = "已完成订单";
			break;
		default:
			break;
		}
		List<OrderInfo> orderList = memberService.getOrderListByParams(params);
		model.addAttribute("haveorder", orderList.size());
		model.addAttribute("orderList", orderList);
		model.addAttribute("title", title);
		return "/mall/orderlist";
	}
	
	

}
